<template>
  <div class="container">
    <div class="app-container">
      <div class="addbtn">
        <el-button size="mini" type="primary" @click="addFormVisible = true"
          >添加角色</el-button
        >
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column align="center" label="角色" width="200">
          <template v-slot="{ row }">
            <el-input
              size="mini"
              v-model="row.editRow.name"
              v-if="row.isEdit"
            ></el-input>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="启用" width="200">
          <!-- 作用域插槽，组件定义了三个参数，row 就是该行的所有数据 -->
          <template v-slot="{ row }">
            <el-switch
              v-model="row.editRow.state"
              active-color="#409eff"
              inactive-color="#dcdfe6"
              :active-value="1"
              :inactive-value="0"
              v-if="row.isEdit"
            />
            <span v-else>{{
              row.state === 1 ? "启用" : row.state === 0 ? "未启用" : "无"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template v-slot="{ row }">
            <el-input
              size="mini"
              v-model="row.editRow.description"
              v-if="row.isEdit"
              type="textarea"
            ></el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="submitEdit(row)"
                >确定</el-button
              >
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button
                type="text"
                size="mini"
                @click="assignPermission(row.id)"
                >分配权限</el-button
              >
              <el-button type="text" size="mini" @click="editNow(row)"
                >编辑</el-button
              >
              <el-popconfirm
                title="确定要删除此角色吗？"
                @onConfirm="deleteFn(row.id)"
              >
                <el-button slot="reference" type="text" size="mini"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" class="page">
        <el-pagination
          layout="prev, pager, next"
          @current-change="currentChange"
          :current-page.sync="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
        >
        </el-pagination>
      </el-row>
      <!-- 弹窗 -->
      <el-dialog
        title="新增角色"
        :visible.sync="addFormVisible"
        @close="closeFn"
        width="500px"
      >
        <el-form
          ref="addForm"
          :model="addForm"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="addForm.name"
              autocomplete="off"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="启用">
            <el-switch
              v-model="addForm.state"
              active-color="#409eff"
              inactive-color="#dcdfe6"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              style="width: 300px"
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="addForm.description"
            >
            </el-input>
          </el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="7">
              <el-button type="primary" size="mini" @click="submit"
                >确 定</el-button
              >
              <el-button size="mini" @click="closeFn">取 消</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <el-tree
          ref="permissionTree"
          :data="permissionData"
          :props="{ label: 'name' }"
          show-checkbox
          default-expand-all
          node-key="id"
          check-strictly
        />
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="submitAssign">确认</el-button>
            <el-button size="mini" @click="showPermissionDialog=false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getRoleListApi,
  addRoleApi,
  editRoleApi,
  deleteRoleApi,
  getPermissionListApi,
  getRoleInfoApi,
  assignPermissionApi
} from "@/api/role";
import { transListToTree } from "@/utils/index";
export default {
  name: "Role",
  data() {
    return {
      addForm: {
        name: "",
        description: "",
        state: 1,
      },
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        description: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      permissionData: [],
      addFormVisible: false,
      showPermissionDialog: false,
      currentId:null,
      tableData: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0,
      },
    };
  },
  created() {
    this.getRoleList();
    this.getPermissionList();
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleListApi({ ...this.pageParams });
      this.tableData = rows;
      this.tableData.forEach((item) => {
        this.$set(item, "isEdit", false);
        // 编辑时不能和原数据进行双向绑定，否则点取消也会改变原数据
        // 需要复制一份原数据用于编辑时双向绑定，拿这份数据进行接口请求
        this.$set(item, "editRow", {
          name: item.name,
          description: item.description,
          state: item.state,
        });
      });
      this.pageParams.total = total;
    },
    async getPermissionList() {
      const res = await getPermissionListApi();
      this.permissionData = transListToTree(res, 0);
    },
    async assignPermission(id) {
      this.currentId = id
      const { permIds } = await getRoleInfoApi(id);
      this.showPermissionDialog = true;
      // 优化 防闪
      this.$refs.permissionTree
        ? this.$refs.permissionTree.setCheckedKeys(permIds)
        : this.$nextTick(() => {
            // 直接在tree上绑定的数组不是响应式的，要用tree上的方法setCheckedKeys
            // vue更新dom是异步的，第一次点击的时候代码执行到这里dom还没渲染，会造成undefined，所以要$nextTick
            this.$refs.permissionTree.setCheckedKeys(permIds);
          });
    },
    async submitAssign(){
      const permIds = this.$refs.permissionTree.getCheckedKeys()
      await assignPermissionApi({id:this.currentId,permIds})
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    currentChange() {
      this.getRoleList();
    },
    closeFn() {
      this.addFormVisible = false;
      this.$refs.addForm.resetFields();
    },
    submit() {
      this.$refs.addForm.validate(async (pass) => {
        if (pass) {
          await addRoleApi({ ...this.addForm });
          this.$message.success("添加角色成功");
          this.closeFn();
          this.getRoleList();
        }
      });
    },
    editNow(row) {
      row.isEdit = true;
      row.editRow.name = row.name;
      row.editRow.state = row.state;
      row.editRow.description = row.description;
    },
    cancelEdit(row) {
      row.isEdit = false;
    },
    async submitEdit(row) {
      if (!row.editRow.name || !row.editRow.description) {
        return this.$message.warning("修改内容不得为空！");
      }
      await editRoleApi({ ...row.editRow, id: row.id });
      row.isEdit = false;
      this.$message.success("修改成功");
      this.getRoleList();
    },
    async deleteFn(id) {
      await deleteRoleApi(id);
      this.$message.success("删除成功");
      if (this.tableData.length === 1) {
        this.pageParams.page--;
      }
      this.getRoleList();
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  .addbtn {
    padding: 10px;
  }
  .page {
    padding: 10px;
  }
}
</style>
